﻿using System;
using System.Collections.Generic;
using System.Text;
using FDSimpleModelGenerator.Common;
using FDSimpleModelGenerator.DapperAccessor;
using FDSimpleModelGenerator.IServices;
using Microsoft.Extensions.DependencyInjection;

namespace FDSimpleModelGenerator.Services.SqlServer
{
    public static class SqlServerGeneratorExtensions
    {
        /// <summary>
        /// 使用Sql Server生成器
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSqlServerGenerator(this IServiceCollection services)
        {
            // 以防止多次注入DapperDbAccessor
            services.Remove(new ServiceDescriptor(typeof(IDbAccessor), typeof(DapperDbAccessor),
                ServiceLifetime.Transient));
            services.AddTransient<IDbAccessor, DapperDbAccessor>();
            services.AddTransient<IDbConfigResolver, SqlServerDbConfigResolver>();
            services.AddSingleton<IGenerateModelService, GenerateModelSqlServerService>();
            services.AddTransient<IDatabaseTableInfoService, SqlServerDatabaseTableInfoService>();
            services.AddTransient<IGenerateTableService, SqlServerGenerateTableService>();
            return services;
        }

        /// <summary>
        /// 替换字符串，目标值为空，则跳过
        /// </summary>
        /// <param name="source">原串</param>
        /// <param name="oldValue">被替换串</param>
        /// <param name="newValue">替换串</param>
        /// <returns></returns>
        public static string IgnoreNullReplace(this string source, string oldValue, string newValue)
        {
            if (source.IsNullOrEmpty() || oldValue.IsNullOrEmpty() || newValue.IsNullOrEmpty())
            {
                return source;
            }

            return source.Replace(oldValue, newValue);
        }
    }
}
